package com.ztman.rxjava.model.entityExtends.upload;

import com.squareup.okhttp.RequestBody;
import com.ztman.rxjava.model.baseEntity.BaseResponse;
import com.ztman.rxjava.server.retrofit.OnNetRequestListener;
import com.ztman.rxjava.server.retrofit.RetrofitService;

import java.util.Map;

import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action0;
import rx.schedulers.Schedulers;

/**
 * Created by YJH on 2017/11/30.
 * 功能：实现接口-网络数据的请求
 */

public class UploadModelIml implements UploadModel {
    //单文件上传方法
    @Override
    public void setUploadParams(Map<String, RequestBody> params, long id, final OnNetRequestListener listener) {
        Observable<BaseResponse<UoloadFileMulti>> observable = RetrofitService.getInstance()
                .createUploadFileApi().uploadFileMulti(params, id);

        observable.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .doOnSubscribe(new Action0() {
                    @Override
                    public void call() {
                        listener.onRequestStart();
                    }
                }).subscribe(new Subscriber<BaseResponse<UoloadFileMulti>>() {
            @Override
            public void onCompleted() {
                listener.onRequestFinish();
            }

            @Override
            public void onError(Throwable e) {
                listener.onRequestFailure(e);
                listener.onRequestFinish();
            }

            @Override
            public void onNext(BaseResponse<UoloadFileMulti> uploadFileBaseResponse) {
                //成功获取到数据并转换类型输出
                listener.onRequestSuccess(uploadFileBaseResponse);
            }
        });
    }


    //多文件上传方法
    @Override
    public void setUploadParams(RequestBody requestBody, long id, final OnNetRequestListener listener) {
                Observable<BaseResponse<UploadFile>> observable = RetrofitService.getInstance()
                .createUploadFileApi().uploadFileSingle(requestBody, id);

        observable.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .doOnSubscribe(new Action0() {
                    @Override
                    public void call() {
                        listener.onRequestStart();
                    }
                }).subscribe(new Subscriber<BaseResponse<UploadFile>>() {
            @Override
            public void onCompleted() {
                listener.onRequestFinish();
            }

            @Override
            public void onError(Throwable e) {
                listener.onRequestFailure(e);
                listener.onRequestFinish();
            }

            @Override
            public void onNext(BaseResponse<UploadFile> uploadFileBaseResponse) {
                //成功获取到数据并转换类型输出
                listener.onRequestSuccess(uploadFileBaseResponse);
            }
        });
    }
}
